<?php
    if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])){exit();}
    include_once("backend/db/db_cse305.php")
?>
<div id="customeraccountwidget" class="widgetcontainer" <?php if (!isLoggedIn() || $_SESSION['User']->UserType != "Customer") echo "style='display:none;'"?>>
    <div id="customeraccountheading" class="widgetheading">
        Your Accounts<img src="images/plus.jpg"/>
    </div>
    <div id="customeraccount" class="widget">
        <script type="text/javascript">
            $("#customeraccountheading").data("divlink", $("#customeraccount"));
            $("#customeraccount").data("heading", $("#customeraccountheading"));
            $("#customeraccountheading").data("clear", function() {
                customer_accounts = null;
                cur_account = null;
                $("#customer_accounts_table_body").empty();
                $("#customer_account_table_body").empty();
                $("#customer_order_table_body").empty();
                $("#customer_order_detail_table_body").empty();
            });
        </script>
        <div id="clear"></div>
        <div>
            
            Click on an account to view more details.
            <table id="customer_accounts_table" class="rounded-corner sortable">
                <thead style="text-align:center;"><tr>
                    <th>Account ID</th><th>Date Opened</th><th>Account Value</th><th>Account Volume</th>
                </tr></thead>
                <tbody id="customer_accounts_table_body">
                </tbody>
            </table>
            <hr />
            <h3>Current Account Holdings<span id="customer_account_holding_id"></h3>
            <table id="customer_account_table" class="rounded-corner sortable">
                <thead style="text-align:center;"><tr>
                    <th>Stock Symbol</th><th>Stock Name</th><th>Number of Shares</th><th>Share Value</th><th>Total Value</th>
                </tr></thead>
                <tbody id="customer_account_table_body">
                </tbody>
            </table>
            <hr />
            <h3>Account Orders<span id="customer_account_order_id"></h3>
            <b>Click on an order to view its transaction history.</b>
            <table id="customer_order_table" class="rounded-corner sortable">
                <thead style="text-align:center;"><tr>
                    <th>Order ID</th><th>Stock Symbol</th><th>Order Type</th><th>Latest Transaction Time</th>
                </tr></thead>
                <tbody id="customer_order_table_body">
                </tbody>
            </table>
            
            <hr />
            <h3>Order Details<span id="customer_order_detail_id"></span></h3>
            <table id="customer_order_detail_table" class="rounded-corner sortable">
                <thead style="text-align:center;"><tr>
                    <th>Transaction ID</th><th>Number of Shares</th><th>Price/Transaction Type</th><th>Percentage</th><th>Fee</th><th>Employee</th><th>Transaction Time</th>
                </tr></thead>
                <tbody id="customer_order_detail_table_body">
                </tbody>
            </table>
        </div>
        
    </div>
    <br />
</div>
<script type="text/javascript">
    <?php if (isLoggedIn() && $_SESSION['User']->UserType == "Customer") echo "$(document).ready(loadAccountInfo);" ?>
    function loadAccountInfo() {
        $.ajax({
            type: 'POST',
            url: '../backend/customer_info.php',
            dataType: 'json',
            success: function(data) {
                customer_accounts = data;
                //<th>Account ID</th><th>Date Opened</th><th>Account Value</th><th>Account Volume</th>
                $.each(customer_accounts, function(accountID, acc) {
                    var row = $("<tr>");
                    row.append($("<td>").text(accountID));
                    row.append($("<td>").text(acc["DateOpened"]));
                    row.append($("<td style='text-align:right;'>").text(priceFormat(acc["Value"])));
                    row.append($("<td style='text-align:right;'>").text(acc["Volume"]));
                    $("#customer_accounts_table_body").append(row);
                });
                $("#customer_accounts_table_body tr").bind('click', function() {
                    $("#customer_account_table_body").empty();
                    var account = customer_accounts[$($(this).find("td")[0]).text()];
                    cur_account = account;
                    //<th>Stock Symbol</th><th>Stock Name</th><th>Number of Shares</th><th>Account Value</th><th>Account Volume</th>
                    $.each(account["Holdings"], function(key, stock) {
                        var row = $("<tr>");
                        row.append($("<td>").text(stock["StockSymbol"]));
                        row.append($("<td>").text(stock["StockName"]));
                        row.append($("<td style='text-align:right;'>").text(stock["Shares"]));
                        row.append($("<td style='text-align:right;'>").text(priceFormat(stock["SharePrice"])));
                        row.append($("<td style='text-align:right;'>").text(priceFormat(stock["Shares"] * stock["SharePrice"])));
                        $("#customer_account_table_body").append(row);
                    });
                    var last = $("<tr style='font-weight:bold;'>");
                    last.append($("<td>").text("Total"));
                    last.append($("<td>"));
                    last.append($("<td style='text-align:right;'>").text($($(this).find("td")[3]).text()));
                    last.append($("<td style='text-align:right;'>"));
                    last.append($("<td style='text-align:right;'>").text($($(this).find("td")[2]).text()));
                    $("#customer_account_table_body").append(last);
                    
                    $("#customer_order_table_body").empty();
                    $.each(account["Orders"], function(OrderID, Order) {
                        var row = $("<tr>");
                        row.append($("<td>").text(OrderID));
                        row.append($("<td>").text(Order["StockSymbol"]));
                        row.append($("<td>").text(Order["OrderType"]));
                        
                        var lastTime = null;
//                        var lastTime = new Date(
//                            Order["Time"].substr(0, 4), 
//                            Order["Time"].substr(5, 2), 
//                            Order["Time"].substr(8, 2), 
//                            Order["Time"].substr(11, 2), 
//                            Order["Time"].substr(14, 2),
//                            Order["Time"].substr(17, 2), 0);;
                        $.each(Order["TransactionHistory"], function(TransactKey, Transact) {
                            var date = 
                                new Date(
                                    Transact["Time"].substr(0, 4), 
                                    Transact["Time"].substr(5, 2), 
                                    Transact["Time"].substr(8, 2), 
                                    Transact["Time"].substr(11, 2), 
                                    Transact["Time"].substr(14, 2),
                                    Transact["Time"].substr(17, 2), 0);
                            if (lastTime == null) {
                                lastTime = date;
                            } else {
                                if (date > lastTime) {
                                    lastTime = date;
                                }
                            }
                        });
                        row.append($("<td>").text(lastTime.getFullYear() + "-" + pad(lastTime.getMonth() + 1) + "-" + pad(lastTime.getDate()) + " " + lastTime.toLocaleTimeString()));
                        $("#customer_order_table_body").append(row);
                    });
                    $("#customer_order_table_body tr").bind('click', function() {
                        //alert($($(this).find("td")[0]).text());
                        
                        $("#customer_order_detail_table_body").empty();
                        var order = cur_account["Orders"][$($(this).find("td")[0]).text()];
                        $.each(order["TransactionHistory"], function(key, transact) {
                            var row = $("<tr>");
                            row.append($("<td>").text(transact["TransactionID"]));
                            row.append($("<td>").text(transact["NumShares"]));
                            row.append($("<td>").text(transact["PriceType"]));
                            if (transact["Percentage"] == null) {
                                row.append($("<td>").text("N/A"));
                            } else {
                                row.append($("<td>").text(String(transact["Percentage"]) + "%"));
                            }
                            row.append($("<td>").text(transact["Fee"]));
                            row.append($("<td>").text(transact["EmployeeName"] + " (" + transact["EmployeeID"] + ")"));
                            var date = 
                                    new Date(
                                    transact["Time"].substr(0, 4), 
                                    transact["Time"].substr(5, 2), 
                                    transact["Time"].substr(8, 2), 
                                    transact["Time"].substr(11, 2), 
                                    transact["Time"].substr(14, 2),
                                    transact["Time"].substr(17, 2), 0);
                            row.append($("<td>").text(date.getFullYear() + "-" + pad(date.getMonth() + 1) + "-" + pad(date.getDate()) + " " + date.toLocaleTimeString()));
                            $("#customer_order_detail_table_body").append(row);
                        });
                        $("#customer_order_detail_id").text(" - Order ID " + $($(this).find("td")[0]).text());
                    });
                    $("#customer_account_holding_id").text(" - Account ID " + $($(this).find("td")[0]).text());
                    $("#customer_account_order_id").text(" - Account ID " + $($(this).find("td")[0]).text());
                });
    
            },                    
            error: function(XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    }
    function pad(s) {
        var ret = String(s);
        while (ret.length < 2) {
            ret = "0" + ret;
        }
        return ret;
    }
</script>